<template>
  <div class="page-user">
    <div class="tree-list">
      <Department />
    </div>
    <a-card
      class="general-card list-table"
      title="员工与部门管理"
      :body-style="{height: 'calc(100% - 72px)'}"
    >
      <template #extra>
        <a-space :size="8">
          <a-input v-model="searchForm.name" placeholder="请输入员工姓名/手机号" />

          <a-button type="primary" @click="handleEdit({}, 'add')">
            <template #icon>
              <icon-plus />
            </template>
            添加员工
          </a-button>
          <a-dropdown>
            <a-button>
              <icon-more />
            </a-button>
            <template #content>
              <a-doption>批量导入</a-doption>
              <a-doption>批量导出</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
      <div class="card-body">
        <a-row style="margin-bottom: 16px;">
          <a-col flex="auto">
            <div class="table-title">
              <span>研发部</span>
              <div class="desc">所有员工 <span class="color-block">1</span>人，已激活 <span class="color-block">1</span>
                人，未激活 <span class="color-block">1</span> 人，停用
                <span>1</span> 人
              </div>
            </div>
          </a-col>
          <a-col flex="334px">
            <a-space :size="16">
              <a-checkbox value="1">包含子部门</a-checkbox>
              <a-select v-model="searchForm.status" :options="statusOptions" placeholder="所有员工" />
            </a-space>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />
        <div class="table-wrapper">
          <div class="table-box">
            <a-table
              bordered
              row-key="id"
              :data="tableData"
              :scroll="scrollPercent"
              :loading="pageLoading"
              :pagination="pageData"
            >
              <template #columns>
                <a-table-column title="员工姓名" data-index="name"></a-table-column>
                <a-table-column title="部门" data-index="department_name"></a-table-column>
                <a-table-column title="岗位" data-index="post_name"></a-table-column>
                <a-table-column title="手机号码" data-index="mobile"></a-table-column>
                <a-table-column title="状态" data-index="status">
                  <template #cell="{ record }">
                    <DictBadge :options="statusOptions" :value="record.status"/>
                  </template>
                </a-table-column>
                <a-table-column title="创建时间" data-index="create_time"></a-table-column>
                <a-table-column title="操作" :width="160">
                  <template #cell="{ record }">
                    <a-button type="text" @click="handleEdit(record, 'edit')">编辑</a-button>
                    <a-button type="text" @click="handleEdit(record, 'add')">新增</a-button>
                    <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                      <a-button v-if="record.id !== 10000" type="text" danger link>删除</a-button>
                    </a-popconfirm>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 新增 & 编辑 弹窗 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="`${formState.id ? '编辑' : '创建'}员工`"
      width="680px"
      :footer="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        auto-label-width
        @submit="handleSubmit"
      >

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="员工姓名" field="name">
              <a-input v-model="formState.name" placeholder="请输入员工姓名" :maxlength="20"></a-input>
            </a-form-item>
            <a-form-item label="手机号码" field="mobile">
              <a-input v-model="formState.mobile" placeholder="请输入手机号码" :maxlength="20" />
            </a-form-item>
            <a-form-item label="邮箱" field="email">
              <a-input v-model="formState.email" placeholder="请输入邮箱" :maxlength="100" />
            </a-form-item>
            <a-form-item label="性别" field="gender">
              <a-radio-group v-model="formState.gender">
                <a-radio v-for="item in genderOptions" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属部门" field="department_id">
              <a-tree-select
                v-model="formState.department_id"
                :data="departOptions"
                :field-names="fieldNames"
                placeholder="请选择所属部门"
              ></a-tree-select>
            </a-form-item>
            <a-form-item label="岗位" field="post_id">
              <a-select
                v-model="formState.post_id"
                :data="departOptions"
                placeholder="请选择岗位"
              ></a-select>
            </a-form-item>
            <a-form-item label="角色" field="role_id">
              <a-select
                v-model="formState.role_id"
                :data="roleOptions"
                placeholder="请选择角色"
              ></a-select>
            </a-form-item>
            <a-form-item label="状态" field="status">
              <a-radio-group v-model="formState.status">
                <a-radio v-for="item in statusOptions" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formState.remark"
            placeholder="简介"
            auto-size
            :maxlength="200"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <div class="form-footer">
          <a-button key="submit" html-type="submit" type="primary" :loading="pageLoading">确 定</a-button>
          <a-button class="ml-24" @click="handleCancel">取 消</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import get from "lodash/get";
import { addUser, updateUser, delUser, getUserList, getUserDetail } from "@/api/user.ts";
import { statusOptions, genderOptions } from "@/enums/status";
import { IconMore } from "@arco-design/web-vue/es/icon";
import Department from "./department.vue";

export default defineComponent({
  components: { IconMore, Department },
  data() {
    return {
      pageLoading: false,
      statusOptions,
      genderOptions,
      scrollPercent: {
        y: "100%"
      },
      tableData: [],
      pageData: {
        pageSize: 50,
        current: 1,
        total: 0
      },
      // 搜索表单
      searchForm: {
        number: "",
        name: "",
        contentType: "",
        filterType: "",
        createdTime: [],
        status: ""
      },
      // 部门选择
      departOptions: [],
      fieldNames: {
        title: "name",
        key: "id",
        children: "children"
      },
      // 岗位
      postOptions: [],
      // 角色
      roleOptions: [],
      // 创建弹窗
      dialogVisible: false,
      formState: {
        id: undefined,
        department_id: undefined,
        post_id: undefined,
        role_id: undefined,
        name: undefined,
        mobile: undefined,
        email: undefined,
        gender: 0,
        status: 1,
        remark: undefined
      },
      formRules: {
        department_id: [{ required: true, message: "所属部门不能为空", trigger: "change" }],
        post_id: [{ required: true, message: "岗位不能为空", trigger: "change" }],
        name: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        mobile: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
        // email: [{ required: false, type: "email", message: "邮箱不正确", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.fetchTableData();
  },
  methods: {
    async fetchTableData(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          ...this.pageData
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const { data, code } = await getUserList(params);

        if (code === 200 && data) {
          // for (let i = 0; i < 100; i += 1) {
          //   this.tableData.push([...data.list]);
          // }
          this.tableData = get(data, "list", []);
          this.pageData.current = data.current || 0;
          this.pageData.total = data.total || 0;
        }
      } catch (err) {
        // you can report use errorHandler or other
      } finally {
        this.pageLoading = false;
      }
    },
    handleSearch(current: number) {
      this.fetchTableData({ current });
    },
    // 操作
    handleDelete(rowData) {
      if (!rowData.id) return;

      delUser(rowData).then(res => {
        const { code, msg } = res;

        if (code === 200) {
          this.$message.success(msg || "删除成功！");
          this.fetchTableData();
        } else {
          this.$message.error(msg || "出了点小问题，请稍后重试！");
        }
      });
    },
    // 创建表单
    async handleEdit(rowData: any, type = "add") {
      if (rowData.id && type === "edit") {
        try {
          const { data } = await getUserDetail({ id: rowData.id });
          this.dialogVisible = true;
          this.formState = {
            id: data.id || undefined,
            department_id: data.department_id || undefined,
            post_id: data.post_id || undefined,
            role_id: data.role_id || undefined,
            name: data.name || undefined,
            mobile: data.mobile || undefined,
            email: data.email || undefined,
            gender: data.gender || 0,
            status: data.status || 1,
            remark: data.remark || undefined
          };
        } catch (err) {
          // you can report use errorHandler or other
        }
      } else {
        this.dialogVisible = true;
        this.formState = {
          id: undefined,
          department_id: undefined,
          post_id: undefined,
          role_id: undefined,
          name: undefined,
          mobile: undefined,
          email: undefined,
          gender: 0,
          status: 1,
          remark: undefined
        };
      }
    },
    handleCancel() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.dialogVisible = false;
    },
    async handleSubmit({ values, errors }) {
      console.log("values:", values, "\nerrors:", errors);
      if (!errors) {
        const params = {
          ...this.formState
        };

        this.pageLoading = true;
        try {

          if (params.id) {
            await updateUser(params);
          } else {
            await addUser(params);
          }

          this.$message.success("保存成功！");
          await this.fetchTableData();
          this.handleCancel();
        } catch (err) {
          // you can report use errorHandler or other
        } finally {
          this.pageLoading = false;
        }
      }
    }
  }
});
</script>


<style scoped lang="less">
.page-user {
  position: relative;
  height: 100%;
  padding: 16px 16px 0 272px;

  .tree-list {
    position: absolute;
    top: 16px;
    bottom: 0;
    left: 16px;
    width: 240px;
    overflow: hidden;
    background-color: #fafbfc;
    border-radius: 4px;
  }

  .list-table {
    height: 100%;

    .table-title {
      display: flex;
      font-size: 16px;
      line-height: 32px;

      .desc {
        margin-left: 12px;
        color: #6b778c;
      }
    }

    .card-body {
      display: flex;
      flex-direction: column;
      flex-shrink: 0;
      height: 100%;
      min-height: 0;
      overflow: hidden;

      .table-wrapper {
        position: relative;
        flex: 1;
        min-height: 0;
        overflow: hidden;
        //height: 600px;
        .table-box {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          overflow: hidden;
        }
      }
    }
  }
}

.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
